package com.guojiganzhe.subject.infra.basic.service.impl;

import com.guojiganzhe.subject.common.entity.PageResult;
import com.guojiganzhe.subject.common.enums.SubjectInfoTypeEnum;
import com.guojiganzhe.subject.infra.basic.entity.EsSubjectFields;
import com.guojiganzhe.subject.infra.basic.entity.SubjectInfoEs;
import com.guojiganzhe.subject.infra.basic.es.EsIndexInfo;
import com.guojiganzhe.subject.infra.basic.es.EsRestClient;
import com.guojiganzhe.subject.infra.basic.es.EsSearchRequest;
import com.guojiganzhe.subject.infra.basic.es.EsSourceData;
import com.guojiganzhe.subject.infra.basic.service.SubjectEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
/**
 * 题目Elasticsearch服务实现类
 * 提供题目的Elasticsearch相关操作，包括题目信息的插入和查询功能
 */
@Service
@Slf4j
public class SubjectEsServiceImpl implements SubjectEsService {
    /**
     * 将题目信息插入到Elasticsearch中
     */
    @Override
    public boolean insert(SubjectInfoEs subjectInfoEs) {
        EsSourceData esSourceData = new EsSourceData();
        Map<String, Object> data = convert2EsSourceData(subjectInfoEs);//转换数据格式为map
        esSourceData.setDocId(subjectInfoEs.getDocId().toString());
        esSourceData.setData(data);
        return EsRestClient.insertDoc(getEsIndexInfo(), esSourceData);//插入数据
    }
    /**
     * 将题目信息实体转换为Elasticsearch存储所需的Map格式数据
     */
    private Map<String, Object> convert2EsSourceData(SubjectInfoEs subjectInfoEs) {
        Map<String, Object> data = new HashMap<>();
        data.put(EsSubjectFields.SUBJECT_ID, subjectInfoEs.getSubjectId());
        data.put(EsSubjectFields.DOC_ID, subjectInfoEs.getDocId());
        data.put(EsSubjectFields.SUBJECT_NAME, subjectInfoEs.getSubjectName());
        data.put(EsSubjectFields.SUBJECT_ANSWER, subjectInfoEs.getSubjectAnswer());
        data.put(EsSubjectFields.SUBJECT_TYPE, subjectInfoEs.getSubjectType());
        data.put(EsSubjectFields.CREATE_USER, subjectInfoEs.getCreateUser());
        data.put(EsSubjectFields.CREATE_TIME, subjectInfoEs.getCreateTime());
        return data;
    }
    /**
     * 根据关键字查询题目列表，支持分页和高亮显示
     */
    @Override
    public PageResult<SubjectInfoEs> querySubjectList(SubjectInfoEs req) {
        PageResult<SubjectInfoEs> pageResult = new PageResult<>();
        EsSearchRequest esSearchRequest = createSearchListQuery(req);//构造查询请求条件
        SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);//执行查询

        List<SubjectInfoEs> subjectInfoEsList = new LinkedList<>();
        SearchHits searchHits = searchResponse.getHits();//获取命中的结果集
        if (searchHits == null || searchHits.getHits() == null) {//查询结果为空处理
            pageResult.setPageNo(req.getPageNo());
            pageResult.setPageSize(req.getPageSize());
            pageResult.setRecords(subjectInfoEsList);
            pageResult.setTotal(0);
            return pageResult;
        }
        //转换结果列表
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            SubjectInfoEs subjectInfoEs = convertResult(hit);
            if (Objects.nonNull(subjectInfoEs)) {
                subjectInfoEsList.add(subjectInfoEs);
            }
        }
        //设置结果集
        pageResult.setPageNo(req.getPageNo());
        pageResult.setPageSize(req.getPageSize());
        pageResult.setRecords(subjectInfoEsList);
        pageResult.setTotal(Long.valueOf(searchHits.getTotalHits().value).intValue());
        return pageResult;
    }

    /**
     * 将Elasticsearch查询结果转换为题目信息实体
     * 处理高亮显示字段，并计算匹配度得分
     * @param hit Elasticsearch查询命中的单条记录
     * @return 转换后的题目信息实体
     */
    private SubjectInfoEs convertResult(SearchHit hit) {
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        if (CollectionUtils.isEmpty(sourceAsMap)) {
            return null;
        }
        //转换结果格式
        SubjectInfoEs result = new SubjectInfoEs();
        result.setSubjectId(MapUtils.getLong(sourceAsMap, EsSubjectFields.SUBJECT_ID));
        result.setSubjectName(MapUtils.getString(sourceAsMap, EsSubjectFields.SUBJECT_NAME));

        result.setSubjectAnswer(MapUtils.getString(sourceAsMap, EsSubjectFields.SUBJECT_ANSWER));

        result.setDocId(MapUtils.getLong(sourceAsMap, EsSubjectFields.DOC_ID));
        result.setSubjectType(MapUtils.getInteger(sourceAsMap, EsSubjectFields.SUBJECT_TYPE));
        result.setScore(new BigDecimal(String.valueOf(hit.getScore())).multiply(new BigDecimal("100.00")
                .setScale(2, RoundingMode.HALF_UP)));

        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        //处理name的高亮
        HighlightField subjectNameField = highlightFields.get(EsSubjectFields.SUBJECT_NAME);
        if(Objects.nonNull(subjectNameField)){
            Text[] fragments = subjectNameField.getFragments();//获取高亮片段
            StringBuilder subjectNameBuilder = new StringBuilder();
            for (Text fragment : fragments) {
                subjectNameBuilder.append(fragment);
            }
            result.setSubjectName(subjectNameBuilder.toString());
        }
        //处理答案高亮
        HighlightField subjectAnswerField = highlightFields.get(EsSubjectFields.SUBJECT_ANSWER);
        if(Objects.nonNull(subjectAnswerField)){
            Text[] fragments = subjectAnswerField.getFragments();//获取高亮片段
            StringBuilder subjectAnswerBuilder = new StringBuilder();
            for (Text fragment : fragments) {
                subjectAnswerBuilder.append(fragment);
            }
            result.setSubjectAnswer(subjectAnswerBuilder.toString());
        }
        return result;
    }

    /**
     * 构造题目列表查询的请求参数
     * 包括查询条件、高亮设置、分页参数等
     */
    private EsSearchRequest createSearchListQuery(SubjectInfoEs req) {
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        BoolQueryBuilder bq = new BoolQueryBuilder();//创建布尔查询条件
        //用匹配subject_name字段与关键词的查询条件
        MatchQueryBuilder subjectNameQueryBuilder =
                QueryBuilders.matchQuery(EsSubjectFields.SUBJECT_NAME, req.getKeyWord());
        bq.should(subjectNameQueryBuilder);//should条件
        subjectNameQueryBuilder.boost(2);//设置权重为2
        //用于匹配subject_answer字段与关键词的查询条件
        MatchQueryBuilder subjectAnswerQueryBuilder =
                QueryBuilders.matchQuery(EsSubjectFields.SUBJECT_ANSWER, req.getKeyWord());
        bq.should(subjectAnswerQueryBuilder);//should条件
        //用于匹配subject_type字段与关键词的查询条件
        MatchQueryBuilder subjectTypeQueryBuilder =
                QueryBuilders.matchQuery(EsSubjectFields.SUBJECT_TYPE, SubjectInfoTypeEnum.BRIEF.getCode());
        bq.must(subjectTypeQueryBuilder);//must条件
        bq.minimumShouldMatch(1);//设置 minimumShouldMatch(1)，表示 should 子句中至少需匹配一项（如 subject_name 或 subject_answer）。
        //高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder().field("*").requireFieldMatch(false);
        highlightBuilder.preTags("<span style = \"color:red\">");
        highlightBuilder.postTags("</span>");

        esSearchRequest.setBq(bq);//设置查询条件
        esSearchRequest.setHighlightBuilder(highlightBuilder);//设置高亮设置
        esSearchRequest.setFields(EsSubjectFields.FIELD_QUERY);//设置查询返回字段
        esSearchRequest.setFrom((req.getPageNo() - 1) * req.getPageSize());//设置开始位置
        esSearchRequest.setSize(req.getPageSize());//设置数量
        esSearchRequest.setNeedScroll(false);//不启用滚动查询
        return esSearchRequest;
    }

    /**
     * 获取Elasticsearch索引信息
     */
    private EsIndexInfo getEsIndexInfo() {
        EsIndexInfo esIndexInfo = new EsIndexInfo();
        esIndexInfo.setClusterName("73438a827b55");
        esIndexInfo.setIndexName("subject_index");
        return esIndexInfo;
    }
}